let key = 'CetSoftEEMSysWeb'; //密钥
let iv = '1934577290ABCDEF1264147890ACAE45';
const axios = require('axios');
const {encrypt} = require('./aes');
axios.defaults.withCredentials = true;
let baseUrl = 'https://pynhcx.jnu.edu.cn/ibsjnuweb';

function time(){
  let date = new Date();
  return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
}

function startDate() {
  let date = new Date();
  if (date.getMonth()+1<10) {
    return `${date.getFullYear()}-0${date.getMonth()+1}-01`
  }else{
    return `${date.getFullYear()}-${date.getMonth()+1}-01`
  }
}

function endDate() {
  let date = new Date();
  if (date.getMonth()+2<10) {
    return `${date.getFullYear()}-0${date.getMonth()+2}-01`
  }else{
    return `${date.getFullYear()}-${date.getMonth()+2}-01`
  }
}
// https://pynhcx.jnu.edu.cn/ibsjnuweb/WebService/JNUService.asmx/Login
async function subsidy(id) {
  //pw为密码加密后
  let pw = encrypt(`${id}`, key);
  let login = await axios({
    method: 'post',
    url: `${baseUrl}/WebService/JNUService.asmx/Login`,
    data: {
      password: `${pw}`,
      user: `${id}`
    },
    header: {
      'Content-Type': 'application/json; charset=utf-8',
      'origin': 'https://pynhcx.jnu.edu.cn',
      'referer': 'https://pynhcx.jnu.edu.cn/ibsjnuweb/',
    }
  });
  let header = login.headers;
  let cookie = header['set-cookie'][0];
  let token = {
    userID: login.data.d.ResultList[0].customerId,
    tokenTime: time()
  }
  token = JSON.stringify(token);
  token = encrypt(token, "CetSoftEEMSysWeb");
  token = encodeURI(token);


  let subNum = await axios({
    method:'post',
    url: `${baseUrl}/WebService/JNUService.asmx/GetSubsidy`,
    data:{
      "endDate":endDate(),
      "startDate":startDate()
    },
    headers: {
      "Cookie" : `${cookie.slice(0,43)} jnu-lp=${pw.slice(0,22)}%3D%3D`,
      "Content-Type": "application/json; charset=UTF-8",
      "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36 Edg/89.0.774.50',
      "Token": token,
      "DateTime": `${time()}`
    }
  })

  subNum = subNum.data;
  // console.log(subNum);
  // console.log(typeof(subNum));
  // console.log(subNum.d.ResultList);
  let data = {};
  let electricity = subNum.d.ResultList[0]?subNum.d.ResultList[0].avalibleValue:0;
  let coldWater = subNum.d.ResultList[1]?subNum.d.ResultList[1].avalibleValue:0;
  let hotWater = subNum.d.ResultList[2]?subNum.d.ResultList[2].avalibleValue:0;
  if (subNum.d.ResultList.length != 0) {
    data = {
      electricity:electricity,
      coldWater:coldWater,
      hotWater:hotWater
    }
  }


  if (subNum.d.Success) {
    return data;
  }else{
    return false;
  }
}

// subsidy('T3080A').then(res => {
//   console.log(res);
// })

// console.log(subsidy('T40806'));
// let res = subsidy('T40806');
// console.log(res);
module.exports = {subsidy}